package com.xiaocai.objview;

import android.opengl.GLES20;
import android.opengl.GLUtils;

import java.util.List;

public class ObjView {

    private static final String TAG = "ObjView";

    private final List<ObjDrawInfo> objDrawInfoList;

    private final int POSITION_COMPONENT_COUNT = 3;

    private final int COLOR_COMPONENT_COUNT = 4;

    private final int TEXTURE_COMPONENT_COUNT = 2;

    private final int STRIDE = (POSITION_COMPONENT_COUNT + COLOR_COMPONENT_COUNT + TEXTURE_COMPONENT_COUNT) * Constants.BYTES_PER_FLOAT;

    private ObjLoad objLoad;

    private int width, height;

    public ObjView(ObjLoad objLoad) {
        this.objLoad = objLoad;
        objDrawInfoList = objLoad.getObjDrawInfoList();
    }

    public void setWidthAndHeight(int w, int h) {
        width = w;
        height = h;
    }

    public void draw(ObjViewShaderProgram objViewShaderProgram, float[] mvpMatrix) {
        objViewShaderProgram.setUniforms(mvpMatrix);

        for (int i = 0; i < objDrawInfoList.size(); i++) {
            ObjDrawInfo drawInfo = objDrawInfoList.get(i);

            if (drawInfo.isTransparent) {
                GLES20.glDepthMask(false);
                GLES20.glEnable(GLES20.GL_BLEND);
                GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA);
            } else {
                GLES20.glDepthMask(true);
                GLES20.glDisable(GLES20.GL_BLEND);
            }

            int offset = 0;
            drawInfo.vertexArray.setVertexAttribPointer(offset,
                    objViewShaderProgram.getPositionLocation(),
                    POSITION_COMPONENT_COUNT, STRIDE);

            offset += POSITION_COMPONENT_COUNT;
            drawInfo.vertexArray.setVertexAttribPointer(offset,
                    objViewShaderProgram.getColorLocation(),
                    COLOR_COMPONENT_COUNT, STRIDE);

            offset += COLOR_COMPONENT_COUNT;
            drawInfo.vertexArray.setVertexAttribPointer(offset,
                    objViewShaderProgram.getCoordLocation(),
                    TEXTURE_COMPONENT_COUNT, STRIDE);

            GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, drawInfo.stBitmap, 0);
            GLES20.glGenerateMipmap(GLES20.GL_TEXTURE_2D);
            GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
            GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, objViewShaderProgram.getTextureId());
            GLES20.glUniform1i(objViewShaderProgram.getU_SamplerLocation(), 0);

            GLES20.glDrawArrays(GLES20.GL_TRIANGLES, drawInfo.first, drawInfo.count);

        }
        GLES20.glDisable(GLES20.GL_BLEND);
        GLES20.glDepthMask(true);
    }
}
